package com.utils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;
import java.util.Vector;

public class StringTool {
	static final char NINE = (char) 0x39;
	static final char ZERO = (char) 0x30;
	static final char CH_a = (char) 'a';
	static final char CH_z = (char) 'z';
	static final char CH_A = (char) 'A';
	static final char CH_Z = (char) 'Z';

	public static String appendString(String oldS, int pos, String s) {
		return (oldS.substring(0, pos) + s + oldS.substring(pos));
	}
	
	public static String removeString(Object parentString, String moveString) {
		return (((String) parentString).replaceAll(moveString, ""));
	}

	// To replace a character at a specified position
	public static String replaceCharAt(String s, int pos, char c) {
		// return s.substring(0, pos) + c + s.substring(pos + 1);
		StringBuffer buf = new StringBuffer(s);
		buf.setCharAt(pos, c);
		return buf.toString();
	}

	// replace char with string
	public static String replaceChar(String s, char a, String b) {
		if (s == null)
			return null;

		StringBuffer newString = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char cur = s.charAt(i);
			if (cur == a) {
				newString.append(b);
			} else {
				newString.append(cur);
			}
		}
		return newString.toString();
	}

	// To remove a character
	public static String removeChar(String s, char c) {
		if (s == null)
			return null;

		StringBuffer newString = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char cur = s.charAt(i);
			if (cur != c)
				newString.append(cur);
		}
		return newString.toString();
	}

	// To remove a character at a specified position
	public static String removeCharAt(String s, int pos) {
		// return s.substring(0, pos) + s.substring(pos + 1);
		StringBuffer buf = new StringBuffer(s.length() - 1);
		buf.append(s.substring(0, pos)).append(s.substring(pos + 1));
		return buf.toString();
	}

	// .,*/abc --> abc
	public static String removeSpecialCharsInFront(String s) {
		if (s == null)
			return null;
		String result = "";
		char currChar;
		for (int i = 0; i < s.length(); i++) {
			currChar = s.charAt(i);
			if ((currChar >= ZERO && currChar <= NINE)
					|| (currChar >= CH_a && currChar <= CH_z)
					|| (currChar >= CH_A && currChar <= CH_Z)) {
				result = s.substring(i);
				break;
			}
		}
		return result;
	}

	// "a.b-c" --> "abc"
	public static String removeSpecialCharsInString(String s) {
		if (s == null)
			return null;
		StringBuffer buffer = new StringBuffer();
		char ch;
		for (int i = 0; i < s.length(); i++) {
			ch = s.charAt(i);
			if ((ch >= ZERO && ch <= NINE) || (ch >= CH_a && ch <= CH_z)
					|| (ch >= CH_A && ch <= CH_Z)) {
				buffer.append(ch);
			}
		}
		return buffer.toString();
	}
	
	/**
	 * @param s
	 * @return "a.b,c-d" --> "a b c d"
	 */
	public static String removeSpecialCharsInString2(String s) {
		if (s == null)
			return null;
		StringBuffer buffer = new StringBuffer();
		char ch;
		for (int i = 0; i < s.length(); i++) {
			ch = s.charAt(i);
			if ((ch >= ZERO && ch <= NINE) || (ch >= CH_a && ch <= CH_z)
					|| (ch >= CH_A && ch <= CH_Z) || ch == ' ') {
				buffer.append(ch);
			}
		}
		return buffer.toString();
	}

	public static String onlyOneSpaceBetween2Words(String text) {
		if (text == null)
			return null;

		StringBuffer buffer = new StringBuffer();
		boolean lastCharIsSpace = false;
		for (int i = 0; i < text.length(); i++) {
			char ch = text.charAt(i);
			if (ch == 0x20) {
				if (lastCharIsSpace) {
					continue;
				} else {
					lastCharIsSpace = true;
				}
			} else if (lastCharIsSpace) {
				lastCharIsSpace = false;
			}
			buffer.append(ch);
		}
		return buffer.toString();
	}

	/*
	 * In text: a string having some seperator(s) Out a collection of elements
	 * without (between) seperator
	 */
	public static Collection<String> parseString(String text, String seperator) {
		Vector<String> vResult = new Vector<String>();
		if (text == null || "".equals(text))
			return vResult;

		String tempStr = text.trim();
		String currentLabel = null;

		int index = tempStr.indexOf(seperator);
		while (index != -1) {
			currentLabel = tempStr.substring(0, index).trim();
			// Only accept not null element
			if (!"".equals(currentLabel))
				vResult.addElement(currentLabel);
			tempStr = tempStr.substring(index + 1);
			index = tempStr.indexOf(seperator);
		}
		// Last label
		currentLabel = tempStr.trim();
		if (!"".equals(currentLabel))
			vResult.addElement(currentLabel);
		return vResult;
	}

	final static String[] seperators = { " ", ".", ",", "-", "_", "=", "/" };

	public static Collection<String> parseString(String text) {
		Vector<String> vResult = new Vector<String>();
		if (text == null || "".equals(text))
			return vResult;

		String tempStr = text.trim();
		String currentLabel = null;

		int index = getNextIndex(tempStr);
		while (index != -1) {
			currentLabel = tempStr.substring(0, index).trim();
			// Only accept not null element
			if (!"".equals(currentLabel))
				vResult.addElement(currentLabel);
			tempStr = tempStr.substring(index + 1);
			index = getNextIndex(tempStr);
		}
		// Last label
		currentLabel = tempStr.trim();
		if (!"".equals(currentLabel))
			vResult.addElement(currentLabel);
		return vResult;
	}

	private static int getNextIndex(String text) {
		int index = 0;
		int newIdx = 0;
		boolean hasOne = false;
		for (int i = 0; i < seperators.length; i++) {
			newIdx = text.indexOf(seperators[i]);
			if (!hasOne) {
				if (newIdx != -1) {
					index = newIdx;
					hasOne = true;
				}
			} else if (newIdx != -1) {
				if (newIdx < index) {
					index = newIdx;
				}
			}
		}
		if (!hasOne)
			index = -1;
		return index;
	}

	/* Seperator is any charactor not in rage of (0-9), (a-z), (A-Z) */
	public static Collection<String> parseStringEx(String text) {
		Vector<String> vResult = new Vector<String>();
		if (text == null || "".equals(text))
			return vResult;

		String tempStr = text.trim();
		String currLabel = "";
		char currChar = 0;
		for (int i = 0; i < tempStr.length(); i++) {
			currChar = tempStr.charAt(i);
			if ((currChar >= ZERO && currChar <= NINE)
					|| (currChar >= CH_a && currChar <= CH_z)
					|| (currChar >= CH_A && currChar <= CH_Z)) {
				currLabel = currLabel + currChar;
			} else if (currLabel.length() > 0) {
				vResult.add(currLabel);
				currLabel = new String("");
			}
		}
		// last label
		if (currLabel.length() > 0) {
			vResult.add(currLabel);
		}
		return vResult;
	}

	public static boolean isNumberic(String sNumber) {
		if (sNumber == null || "".equals(sNumber)) {
			return false;
		}
		char ch_max = (char) 0x39;
		char ch_min = (char) 0x30;

		for (int i = 0; i < sNumber.length(); i++) {
			char ch = sNumber.charAt(i);
			if ((ch < ch_min) || (ch > ch_max)) {
				return false;
			}
		}
		return true;
	}

	/** *********************************************************************** */
	/* GENERATE RANDOM STRING OF CHARACTERS */
	/** *********************************************************************** */
	private static char[] charArray = null; // Holds an array of character (used
											// to get the random character for
											// the random string)
	private static char[] numberArray = null;
	
	private static Random random = null; // random object
	// Create an arrays of characters (A--Z, 0--9)
	static {
		int numOfChars = 'Z' - 'A' + 1;
		int numOfDigits = '9' - '0' + 1;
		random = new Random(); // create a random object
		charArray = new char[numOfChars + numOfDigits];
		numberArray = new char[numOfDigits];
		for (int i = 0; i < numOfChars; i++) {
			charArray[i] = (char) ('A' + i);
		}
		for (int i = 0; i < numOfDigits; i++) {
			charArray[numOfChars + i] = (char) ('0' + i);
			numberArray[i] = (char) ('0' + i);
		}
	}

	// returns a random string of chars: A--Z, 0--9
	public String generateRandomString(int length) {
		char[] ch = new char[length];
		for (int i = 0; i < length; i++)
			ch[i] = charArray[random.nextInt(charArray.length)];
		return new String(ch);
	}
	
	public String generateRandomNumber(int length) {
		char[] ch = new char[length];
		for (int i = 0; i < length; i++)
			ch[i] = numberArray[random.nextInt(numberArray.length)];
		return new String(ch);
	}

	/***************************************************************************
	 * Method replaceString
	 * 
	 * @author Nguyen Thien Phuong
	 * 
	 * Replace substring oldStr in string sStr by newStr
	 * 
	 * @param sStr
	 * @param oldStr
	 * @param newStr
	 * @return String
	 **************************************************************************/
	public static String replaceString(String sStr, String oldStr, String newStr) {
		sStr = (sStr == null ? "" : sStr);
		String strVar = sStr;
		String tmpStr = "";
		String finalStr = "";
		int stpos = 0, endpos = 0, strLen = 0;
		while (true) {
			strLen = strVar.length();
			stpos = 0;
			endpos = strVar.indexOf(oldStr, stpos);
			if (endpos == -1)
				break;
			tmpStr = strVar.substring(stpos, endpos);
			tmpStr = tmpStr.concat(newStr);
			strVar = strVar.substring(
					endpos + oldStr.length() > sStr.length() ? endpos : endpos
							+ oldStr.length(), strLen);
			finalStr = finalStr.concat(tmpStr);
			stpos = endpos;
		}
		finalStr = finalStr.concat(strVar);
		return finalStr;
	}

	/***************************************************************************
	 * Method isEmptyOrNul
	 * 
	 * @author Nguyen Thien Phuong
	 * @param input
	 * @return boolean
	 **************************************************************************/
	public static boolean isEmptyOrNul(String input) {
		if (input == null)
			return true;
		if ("".equals(input.trim()))
			return true;
		return false;
	}

	public static String collectionBigDecimal2String(Collection<BigDecimal> c) {
		StringBuffer stringBuff = new StringBuffer();
		if (c == null)
			return null;
		if (c.isEmpty())
			return null;
		BigDecimal big = null;
		for (Iterator<BigDecimal> it = c.iterator(); it.hasNext();) {
			try {
				big = it.next();
				if (big == null)
					continue;
				stringBuff.append(big.toString());
				stringBuff.append(",");
			} catch (Exception e) {
			}
		}
		String string = (stringBuff.toString()).trim();
		if (string.endsWith(","))
			string = string.substring(0, string.length() - 1);
		return string;
	}

	public static String nullToEmpty(Object input) {
		return (input == null ? "" : ("null".equals(input)?"": input.toString()));
	}

	public static java.sql.Date ParserDate(String s, String format) {
		try {
			java.util.Date d = new SimpleDateFormat(format).parse(s);
			return new java.sql.Date(d.getTime());
		} catch (ParseException ex) {
			return new java.sql.Date(0);
		}
	}

	public static String cutEnter(String s) {
		String str = s.replaceAll("\r", "");
		return str;
	}

	public static int findNumber(String sNumber) {

		int result = -1;
		if (sNumber == null || "".equals(sNumber)) {
			return result;
		}
		char ch_max = (char) 0x39;
		char ch_min = (char) 0x30;

		for (int i = 0; i < sNumber.length(); i++) {
			char ch = sNumber.charAt(i);
			if ((ch < ch_min) || (ch > ch_max)) {

			} else {
				result = i;
				break;
			}
		}
		return result;
	}

	public static int findChar(String sNumber) {

		int result = 0;
		if (sNumber == null || "".equals(sNumber)) {
			return result;
		}
		char ch_max = (char) 0x39;
		char ch_min = (char) 0x30;

		for (int i = 0; i < sNumber.length(); i++) {
			char ch = sNumber.charAt(i);
			if ((ch < ch_min) || (ch > ch_max)) {
				result = i;
				break;
			}
		}
		return result;
	}

	public static String chuanHoaTen(String input) {
		if (isEmptyOrNul(input)) return input;
		StringBuffer result = new StringBuffer();
		result.append(input.substring(0,1).toUpperCase());
		for (int i = 1; i < input.length(); i++) {
			String ch = String.valueOf(input.charAt(i));
			if (input.charAt(i-1) == ' ') {
				result.append(ch.toUpperCase());
			} else {
				result.append(ch.toLowerCase());
			}
		}
		return result.toString();
	}	
	public static void main(String[] args) {
		System.out.println(chuanHoaTen("nguYen tHiên phUOnG"));
	}
}
